import Taro, {Component} from '@tarojs/taro'
import {View, Text, ScrollView, Image} from '@tarojs/components'
import {AtActivityIndicator, AtTag, AtDivider} from 'taro-ui'
import './index.scss'
import {connect} from '@tarojs/redux'
import * as actions from '../../actions/product'
import classNames from 'classnames'
import {getWindowHeight} from '../../utils/style'
import Empty from '../../components/Empty'
import Fix from '../../components/Fix'
// import {sliderightshow,fadein} from '../../utils/animate'
// import Loading from '../../components/loading'

const LIST_MODE_TWO_COLUMN = 'LIST_MODE_TWO_COLUMN'//两列
const LIST_MODE_ONE_COLUMN = 'LIST_MODE_ONE_COLUMN'//单列

const DESC = 'DESC'
const ASC = 'ASC'

let page = 1
let fetchState = 'init' //state  'init' 初始化  'pullRefresh' 下拉刷新 2加载更多 'loadMore'
@connect(state => state.product, {...actions})
class List extends Component {
  state = {
    isBottom: false,
    hasMore: false,
    isLoadingMore: false,
    isRefresh: false,
    ids: null,
    initLoading: true,
    inputValue: '',
    sort: DESC,
    option: [
      {text: '上架时间降序', value: DESC},
      {text: '上架时间升序', value: ASC},
    ],
    mode: LIST_MODE_TWO_COLUMN,
    animation: '',
    brandIds: '',
    cateIds: '',
    finishFetch: false,//是否请求完成
    scrollIntoView: '',
    isRecommend: false
  }


  static options = {
    addGlobalClass: true
  }

  config = {
    navigationBarTitleText: '',
    enablePullDownRefresh: true,
    usingComponents: {
      'i-spin': '../../wxComponents/spin/index'
    }
  }

  onShareAppMessage() {
    //解决当前页面不可转发
  }


  getData = (name = '') => {
    // if(!current){
    //     current = this.props.current
    // }
    //
    const {subList, heightArr, masonryList} = this.props
    const {cateIds, sort, brandIds, isRecommend} = this.state
    switch (fetchState) {
      case 'init':
        this.setState({
          isRefresh: true,
          initLoading: true,
          finishFetch: false,
          scrollIntoView: 'top'
        })
        break;
      case 'pullRefresh':
        this.setState({
          isRefresh: true,
          finishFetch: false,
          scrollIntoView: 'top'
        })
        break;
      case 'loadMore':
        this.setState({
          isLoadingMore: true,
          finishFetch: false,
          scrollIntoView: ''
        })
        break;
    }
    // console.log('heightArr',heightArr)
    // console.log('masonryList',masonryList)
    Taro.createSelectorQuery().in(this.$scope).select('#qianqian').boundingClientRect(
      (rects) => {
        // console.log('subList',subList)
        this.props.dispatchSubList({
          cateIds,
          page,
          size: 10,
          subList,
          sort,
          name,
          totalWidth: rects.width,
          heightArr,
          masonryList,
          showMasonry: true,
          brandIds,
          order: isRecommend ? 'viewCount' : 'createTime',
          keyword: this.$router.params.keyword || ''
        }).then((res) => {
          const {pagination} = res.qianqian
          const hasMore = pagination.page * pagination.size < pagination.total
          console.log('hasMore', hasMore)
          switch (fetchState) {
            case 'init':
            case 'pullRefresh':
              this.setState({
                hasMore,
                isRefresh: false,
                triggered: false,
                initLoading: false,
                finishFetch: true
              }, () => {
                Taro.stopPullDownRefresh()
              })
              break;
            case 'loadMore':
              this.setState({
                hasMore,
                isLoadingMore: false,
                finishFetch: true
              })
              break;
          }
          Taro.stopPullDownRefresh()
        })
      }).exec()

  };

  jump(id, name) {
    Taro.navigateTo({
      url: `/pages/detail/index?id=${id}&name=${name}`
    })
  }

  handleChange(value) {
    this.setState({
      inputValue: value
    })
  }

  onActionClick() {
    const {inputValue} = this.state
    this.fetchState = 'init'
    this.getData(inputValue)
  }

  changeMode() {
    const {mode} = this.state
    let scrollIntoView
    if (!this.state.scrollIntoView) {
      scrollIntoView = 'top'
    } else {
      scrollIntoView = this.state.scrollIntoView === 'top' ? 'top1' : 'top'
    }
    this.setState({
      mode: mode == LIST_MODE_ONE_COLUMN ? LIST_MODE_TWO_COLUMN : LIST_MODE_ONE_COLUMN,
      scrollIntoView
    })
  }

  setSort(event) {
    const {sort} = this.state
    if (sort == DESC) {
      this.setState({
        sort: ASC
      }, () => {
        page = 1
        fetchState = 'init'
        this.getData()
      })
    }
    if (sort == ASC) {
      this.setState({
        sort: DESC
      }, () => {
        page = 1
        fetchState = 'init'
        this.getData()
      })
    }
    // const sort = event.detail;
    // this.setState({
    //   sort
    // },()=>{
    //   page = 1
    //   fetchState = 'init'
    //   this.getData()
    // })

  }

  componentWillMount() {
    let {name, brandIds, cateIds, isRecommend} = this.$router.params
    console.log('this.$router.params', this.$router.params)

    this.setState({
      brandIds: brandIds ? brandIds : '',
      cateIds: cateIds ? cateIds : '',
      isRecommend: isRecommend ? isRecommend : false
    })
    Taro.setNavigationBarTitle({
      title: name
    });
  }

  componentDidMount() {
    const pages = Taro.getCurrentPages()
    console.log('pages', pages)
    fetchState = 'init'
    this.getData()
  }

  componentDidShow() {

  }

  componentWillReceiveProps(nextProps) {
    // if(nextProps.current > 0 && this.props.current != nextProps.current){
    //   //切换了menuItem
    //
    //   fetchState = 'init'
    //   page = 1
    //   this.getData(nextProps.current)
    // }
  }

  componentDidUpdate() {

  }


  componentDidHide() {

    // this.setState({
    //   finishFetch:false
    // })
    // this.props.dispatchSubListClear()
  }

  componentWillUnmount() {
    console.log('清除', '')
    page = 1
    fetchState = 'init'
  }

  componentCatchError() {
  }

  render() {
    // const height = getWindowHeight(true)
    //获取rpx
    const height = getWindowHeight(false) + 'px'
    // const height2 = height
    // const {statusHeight,navHeight} = getNavSize()
    // const emptyHeight = getWindowHeight(false) - Taro.pxTransform(10)
    const {subList, total, masonryList} = this.props
    const {
      hasMore,
      isLoadingMore,
      isRefresh,
      initLoading,
      inputValue,
      sort,
      option,
      mode,
      animation,
      finishFetch,
      scrollIntoView,
      isRecommend
    } = this.state
    const wrapperStyle = {overflow: 'auto', height}
    const animationTime = 1.2
    // const scrollIntoView = hasMore && isLoadingMore?'indicator':''
    console.log('scrollIntoView', scrollIntoView)

    const oneHtml = (
      (subList.length > 0 && (finishFetch || isLoadingMore)) ? subList.map((item, index) => {
        return (
          <View className={classNames('cate__item-wrapper', 'animation-scale-up')}
                key={item.id} id={'item' + item.id}
                style={{'animation-delay': (index % 10 + 1) * 0.1 * animationTime + 's', 'opacity': 0}}>
            <View className={classNames('cate__item-horizontal', 'skeleton-bg')}
                  onClick={this.jump.bind(this, item.id, item.name)}>
              <View className="avatar cate__item-left">
                <Image
                  className="avatar skeleton-radius cate__item-img"
                  src={item.bannerImage.url}
                  mode="aspectFill"
                  lazyLoad={true}
                  webp
                />
              </View>
              <View className="title skeleton-rect cate__item-right">
                <Text className="cate__item-title">
                  {item.name}
                </Text>
                {/* <View className="cate__item-content qian__tag">
                        <View className='at-row at-row--wrap at-row__justify--start'>
                            {
                              item.tags && item.tags.length > 0?
                              item.tags.map((item2)=>(
                                <AtTag
                                    size="small"
                                    style={{'margin-right':'6px'}}
                                  >
                                    {item2}
                                </AtTag>
                              )):<View className="cate__item-content-empty"></View>
                            }
                          </View>
                    </View> */}
                <Text className="cate__item-desc" space="ensp" decode={true}>
                  {item.summary}
                </Text>
              </View>
            </View>
          </View>
        );
      }) : null
    )

    // console.log('masonryList', masonryList)
    const elseHtml = (
      <View className="cate_item-masonry">
        {
          (
            (masonryList.length > 0 && (finishFetch || isLoadingMore)) ? masonryList.map((sides) =>
              (
                <View className="cate_item-masonry-item">
                  {sides.map((item, index) =>
                    (
                      <View
                        className={classNames('cate__item-wrapper', 'cate__item-wrapper-vertical', 'animation-fadeIn')}
                        key={item.id} id={'item' + item.id}
                        style={{'animation-delay': (index % 10 + 1) * 0.1 * animationTime + 's', 'opacity': 0}}>
                        <View className={classNames('cate__item-vertical', 'skeleton-bg')}
                              onClick={this.jump.bind(this, item.id, item.name)}>
                          <View className="avatar cate__item-vertical-top">
                            <Image
                              className="avatar skeleton-radius cate__item-img"
                              src={item.bannerImage.url}
                              mode="widthFix"
                              lazyLoad={true}
                              webp
                            />
                          </View>
                          <View className="title skeleton-rect cate__item-vertical-middle">
                            <Text className="cate__item-title">
                              {item.name}
                            </Text>
                            <View className="cate_item-jiange"></View>

                            <Text className="cate__item-desc" space="ensp" decode={true}>
                              {item.summary}
                            </Text>
                          </View>
                        </View>
                      </View>
                    )
                  )}
                </View>
              )
            ) : null
          )
        }
      </View>
    )

    const scrollHtml = (<View className="list-wrapper">
        <ScrollView
          refresherEnabled={false}
          onScrollToLower={this.ScrollToLower.bind(this)}
          className='scroll-box'
          scrollAnchoring
          // scrollY={this.state.scrollY}
          style={{'height': '100%'}}
          lowerThreshold="80"
          scrollIntoView={scrollIntoView}
          onRefresherrefresh={this.triggerRefresh.bind(this)}
          refresherTriggered={false}
          scrollY
          throttle={false}
          scrollWithAnimation={false}>
          {/* <View style={height} > */}
          <Text id="top" style={{height: '0', opacity: '0'}}></Text>
          <Text id="top1" style={{height: '0', opacity: '0'}}></Text>
          {/* style={{'height':'100%'}} */}
          <View className={classNames({'cate__vertial': mode == LIST_MODE_TWO_COLUMN})}>
            {
              (subList.length == 0 && finishFetch) &&
              (<View style={{'height': '100%'}}>
                <Empty></Empty>
              </View>)
            }
            {
              // {'animation-zoom-in-left':mode == LIST_MODE_TWO_COLUMN && index%2 == 0},
              // {'animation-zoom-in-right':mode == LIST_MODE_TWO_COLUMN && index%2 == 1}
            }
            {
              mode == LIST_MODE_ONE_COLUMN && oneHtml
            }
            {
              mode == LIST_MODE_TWO_COLUMN && elseHtml
            }
          </View>
          <View className="list_bottom">
            {
              isLoadingMore ?
                <View className='upDragBox' id="indicator">
                  <AtActivityIndicator className="upDragBox-indicator" content="正在加载中..." size={28}
                                       color='#290b0b'></AtActivityIndicator>
                  {/* <Text className='downText'>正在加载中...</Text> */}
                </View> : null
            }
            {
              (!isLoadingMore && !hasMore && subList.length > 0) ?
                <View className="no-more">
                  <AtDivider content='我是有底线的' fontColor='#dcdcdc' lineColor='#dcdcdc' fontSize="28"/>
                </View> : null
            }
          </View>

        </ScrollView>

      </View>
    )


    return (

      <View id="qianqian">
        <View style={wrapperStyle} className="list-page">
          <Fix></Fix>
          {/* {
              isRefresh?<Loading />:scrollHtml
            } */}
          {/* <Loading spinning={isRefresh}> */}
          {/* {!isRefresh?scrollHtml:<View style={{height}}></View>} */}
          {/* </Loading> */}
          <View className="list-top">
            {/* <View className="list-label">
              <View className="at-icon at-icon-map-pin"></View>
              上海
            </View> */}
            {/* <AtSearchBar
              actionName="搜索"
              placeholder="请输入商品名称"
              value={inputValue}
              onChange={this.handleChange.bind(this)}
              onActionClick={this.onActionClick.bind(this)}
            /> */}
          </View>
          <View className="list-tab">
            <Text className="list-tab-left" decode={true}>
              总计：<Text className="list-tab-left-bold">{total}</Text>&nbsp;件
            </Text>
            <View className="list-tab-right">
              {/* 筛选<Text className="at-icon at-icon-filter"></Text> */}
              <View className="list-tab-right-mode">
                {
                  mode == LIST_MODE_ONE_COLUMN &&
                  <Text className="icon icon-li_paibanleixing_c" onClick={this.changeMode.bind(this)}></Text>
                }
                {
                  mode == LIST_MODE_TWO_COLUMN &&
                  <Text className="icon icon-bujuyi" onClick={this.changeMode.bind(this)}></Text>
                }
              </View>
              <View className="list-tab-right-dropdown">
                {/* <van-dropdown-menu className="list-tab-dropdown" active-color="#ea5555">
                      <van-dropdown-item value={sort} options={option} titleClass="list-tab-dropdown-title"
                        onChange={this.setSort.bind(this)}
                      />
                  </van-dropdown-menu> */}
                {
                  !isRecommend &&
                  <View className="list-tab-sort" onClick={this.setSort.bind(this)}>
                    最新上架
                    {
                      sort == DESC && <Text className='at-icon at-icon-chevron-down'></Text>
                    }
                    {
                      sort == ASC && <Text className='at-icon at-icon-chevron-up'></Text>
                    }
                  </View>
                }
              </View>
            </View>
          </View>
          {
            !initLoading && scrollHtml
          }
          {
            isRefresh && <i-spin size="large" fix fullscreen></i-spin>
          }
        </View>
      </View>


    )
  }

  ScrollToLower() { //滚动到底部事件
    //  this.setState({
    //   isLoading:true
    //  })
    if (this.state.hasMore) {
      console.log('需要加载下一页')
      page++
      fetchState = 'loadMore'
      this.getData(false)
    }
  }

  triggerRefresh() {
    const {isRefresh} = this.state
    if (isRefresh) return;
    // 自定义下拉刷新被触发
    page = 1
    fetchState = 'pullRefresh'
    this.getData()
  }

  onPullDownRefresh() {
    this.triggerRefresh()
  }


}

export default List
